package cn.iocoder.yudao.module.pay.service.order;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.iocoder.yudao.framework.pay.core.client.impl.hftx.wx.WxDeliverGoodsDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 微信小程序发货订单入库
 *
 * @author ε3
 * @date 2025/3/8
 */
@Slf4j
@Service
public class WxLiteOrderService {
    /**
     * 微信appid
     */
    private static final String APP_ID = "wx0c1decbdf5bc4f79";
    /**
     * 微信appSecret
     */
    private static final String APP_SECRET = "e2b0bce50057ed38d06e6d107928e4a1";
    /**
     * TOKEN接口地址
     */
    private static final String TOKEN_REQUEST_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";
    /**
     * 微信小程序-发货信息录入-接口地址
     */
    private static final String REQUEST_URL = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=";
    /**
     * redis中token的key
     */
    private static final String TOKEN_REDIS_KEY = "wx:access_token:";

    private StringRedisTemplate redisService;

    WxLiteOrderService(StringRedisTemplate redisService) {
        this.redisService = redisService;
    }

    /**
     * 微信发货订单录入
     *
     * @param vo 入参
     */
    public void wxLiteOrder(WxDeliverGoodsDTO vo) {
        try {
            String url = REQUEST_URL + getAccessToken();
            /* 获取模拟入参 */
            String param = JSONObject.toJSONString(vo);
            System.out.println("入参 = " + param);
            String result = HttpUtil.post(url, param);
            JSONObject jsonObject = JSON.parseObject(result);
            int errcode = jsonObject.getInteger("errcode");
            String errmsg = jsonObject.getString("errmsg");
            String err = String.format("微信小程序-发货信息录入接口返回信息，code码：%s, msg：%s", errcode, errmsg);
            log.info(err);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 获取accessToken
     *
     * @return accessToken
     */
    private String getAccessToken() {
        /* 先从redis中获取accessToken */
        String accessToken = redisService.opsForValue().get(TOKEN_REDIS_KEY + APP_ID);
        if (StrUtil.isNotEmpty(accessToken)) {
            return accessToken;
        }
        /* 组装请求url */
        String url = TOKEN_REQUEST_URL + "appid=" + APP_ID + "&secret=" + APP_SECRET;
        String result = HttpUtil.get(url);
        JSONObject jsonObject = JSON.parseObject(result);
        redisService.opsForValue().set(TOKEN_REDIS_KEY + APP_ID, jsonObject.getString("access_token"), jsonObject.getIntValue("expires_in"), TimeUnit.SECONDS);
        return jsonObject.getString("access_token");
    }
}
